import sys
import time
import keyboard
import os
import subprocess
import win32clipboard
import win32con
import win32com.client
import pythoncom
from PyQt5.QtWidgets import (QWidget, QLabel, QApplication, QVBoxLayout, 
                           QFrame, QSystemTrayIcon, QMenu, QInputDialog,
                           QDialog, QTextEdit, QPushButton, QHBoxLayout)  # 修改 QLineEdit 为 QTextEdit
from PyQt5.QtGui import QFont, QColor, QIcon, QPalette
from PyQt5.QtCore import Qt, QTimer, QPoint
from PyQt5.QtCore import pyqtSignal

# 自定义带回车信号的 QTextEdit
class TextEditWithEnter(QTextEdit):
    enter_pressed = pyqtSignal()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            self.enter_pressed.emit()
        else:
            super().keyPressEvent(event)

class FloatingTimeWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 周几的中文映射
        self.weekday_map = {
            'Mon': '周一',
            'Tue': '周二',
            'Wed': '周三',
            'Thu': '周四',
            'Fri': '周五',
            'Sat': '周六',
            'Sun': '周日'
        }
        self.initUI()

    def initUI(self):
        # 设置窗口置顶、无边框、无任务栏图标
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool)
        # 设置窗口背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 创建一个布局
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(5)  # 设置标签之间的间距
        
        # 日期标签
        self.date_label = QLabel(self)
        self.date_label.setFont(QFont('Arial', 16, QFont.Bold))
        self.date_label.setAlignment(Qt.AlignCenter)  # 设置居中对齐
        
        # 时间标签
        self.label = QLabel(self)
        self.label.setFont(QFont('Arial', 30, QFont.Bold))
        self.label.setAlignment(Qt.AlignCenter)  # 设置居中对齐
        
        # 任务标签
        self.task_label = QLabel(self)
        self.task_label.setFont(QFont('Arial', 20))  # 增大任务文字大小
        self.task_label.setAlignment(Qt.AlignCenter)
        self.task_label.setWordWrap(True)  # 允许文本自动换行
        self.task_label.setTextFormat(Qt.RichText)  # 确保支持富文本
        
        # 设置样式
        self.setStyleSheet("""
            QWidget {
                background-color: rgba(0, 0, 0, 80);
                border-radius: 0px;
                padding: 0px;
            }
            QLabel {
                color: rgba(110, 202, 250, 192);
            }
        """)
        
        layout.addWidget(self.date_label)
        layout.addWidget(self.label)
        layout.addWidget(self.task_label)
        self.setLayout(layout)
        
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)
        
        # 允许鼠标拖动窗口
        self.mousePressPos = None
        self.mouseMovePos = None
        
        # 初始更新时间
        self.update_time()
        self.show()
        
        # 显示输入对话框
        self.show_input_dialog()
        
        # 打印调试信息
        print(f"程序已启动，请查看屏幕顶部中央位置\nCtrl+Y退出")

    def update_time(self):
        # 更新日期
        current_date = time.strftime('%Y年%m月%d日 %a')
        # 将英文周几转换为中文
        for eng, chn in self.weekday_map.items():
            current_date = current_date.replace(eng, chn)
        
        # 使用 HTML 格式将周几部分设置为红色
        parts = current_date.split(' ')
        date_part = parts[0]
        weekday_part = parts[1]
        date_html = f"{date_part} <span style='color: red;'>{weekday_part}</span>"
        self.date_label.setText(date_html)
        
        # 更新时间，将小时部分设置为红色
        current_time = time.strftime('%H:%M:%S')
        hours = current_time.split(':')[0]
        minutes_seconds = current_time.split(':')[1:]
        
        # 使用 HTML 格式设置不同颜色
        time_html = f'<span style="color: red;">{hours}</span>:{":".join(minutes_seconds)}'
        self.label.setText(time_html)
        
        # 获取屏幕信息
        screen_geometry = QApplication.desktop().availableGeometry()
        
        # 调整窗口大小为合适的尺寸
        self.adjustSize()
        
        # 计算窗口位置（屏幕中央顶部）
        x = (screen_geometry.width() - self.width()) // 2
        y = 10  # 固定距离顶部10像素
        
        # 移动窗口到指定位置
        self.move(x, y)
        
    def show_input_dialog(self):
        # 创建自定义对话框
        dialog = QDialog(self)
        dialog.setWindowTitle('输入时钟任务：')
        dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Window)  # 确保对话框显示在最前面
        
        # 设置对话框样式，只使用黑白配色
        dialog.setStyleSheet("""
            QDialog {
                background-color: #ffffff;
            }
            QTextEdit {
                background-color: #ffffff;
                color: #000000;
                border: 2px solid #000000;
                border-radius: 5px;
                padding: 10px;
                font-size: 26px; /* 将字体大小设置为 26px */
                min-width: 300px;
                min-height: 100px;
                selection-background-color: #000000;
                selection-color: white;
            }
            QPushButton {
                background-color: #000000;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 16px;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #333333;
            }
            QPushButton:pressed {
                background-color: #666666;
            }
            QLabel {
                color: #000000;
                font-size: 18px;
                font-weight: bold;
                padding: 10px;
            }
        """)
        
        # 创建布局
        layout = QVBoxLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建标签
        label = QLabel('下次切换任务Ctrl+Windows+Alt+X；\nCtrl+Windows+Alt+H查看历史\n悬浮时间输入历史history.txt')
        # 设置标签文字颜色为黑色
        label.setStyleSheet("color: #000000; font-size: 18px; font-weight: bold; padding: 10px;")
        
        # 创建输入框，使用自定义带回车信号的 QTextEdit
        input_field = TextEditWithEnter()
        # 显式设置字体大小
        font = input_field.font()
        font.setPointSize(26)
        input_field.setFont(font)
        input_field.setFocus()  # 自动获取焦点

        # 确保对话框和输入框都获得焦点
        dialog.activateWindow()
        dialog.raise_()
        input_field.setFocus()  # 再次确保输入框获得焦点
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(15)
        
        # 创建按钮
        ok_button = QPushButton('确定')
        cancel_button = QPushButton('取消')
        
        # 添加按钮到布局
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)
        
        # 添加所有控件到主布局
        layout.addWidget(label)
        layout.addWidget(input_field)
        layout.addLayout(button_layout)
        
        dialog.setLayout(layout)
        
        # 连接信号
        ok_button.clicked.connect(dialog.accept)
        cancel_button.clicked.connect(dialog.reject)
        input_field.enter_pressed.connect(dialog.accept)  # 按回车键确认

        def save_to_file():
            text = input_field.toPlainText().strip()
            if text:
                try:
                    # 在 from 前添加中文逗号
                    current_time = time.strftime('\n%H:%M:%S_start_%m月%d日')
                    # 使用 HTML 格式设置不同字体大小，将 current_time 字体设为 14px
                    text_html = f"{text}<br><span style='font-size: 20px;'>{current_time}</span>"
                    self.task_label.setText(text_html)

                    full_text = f"{text}{current_time}\n"
                    script_dir = os.path.dirname(os.path.abspath(__file__))
                    file_path = os.path.join(script_dir, "悬浮时间输入历史history.txt")
                    with open(file_path, "a", encoding="utf-8") as f:
                        f.write(full_text)

                    # 将输入文本复制到基础剪贴板
                    clipboard = QApplication.clipboard()
                    clipboard.setText(text)

                    # 将输入文本添加到 Windows 剪贴板历史记录
                    pythoncom.CoInitialize()
                    data_object = win32com.client.Dispatch("DataObject")
                    data_object.SetText(text)
                    data_object.PutInClipboard()
                    pythoncom.CoUninitialize()

                    print("文本已成功复制到剪贴板和剪贴板历史记录")
                except Exception as e:
                    print(f"保存文本或复制到剪贴板时出错: {e}")

        dialog.accepted.connect(save_to_file)
        
        # 设置对话框大小
        dialog.setFixedSize(400, 300)  # 增大对话框高度

        # 让对话框一打开就获得焦点
        dialog.activateWindow()
        dialog.raise_()
        
        # 显示对话框并获取结果
        dialog.exec_()

    # 添加鼠标事件处理，使窗口可拖动
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.mousePressPos = event.globalPos()
            self.mouseMovePos = event.globalPos()
        super().mousePressEvent(event)
            
    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            curr_pos = self.mapToGlobal(self.pos())
            delta = QPoint(event.globalPos() - self.mouseMovePos)
            self.move(curr_pos.x() + delta.x(), curr_pos.y() + delta.y())
            self.mouseMovePos = event.globalPos()
        super().mouseMoveEvent(event)

    def closeEvent(self, event):
        # 忽略关闭事件，防止窗口被关闭
        event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 禁用任务栏显示
    app.setQuitOnLastWindowClosed(False)
    ex = FloatingTimeWidget()
    
    # 注册全局热键
    try:
        # 双引号包裹脚本路径，避免空格问题
        script_path = f'"{os.path.abspath(__file__)}"'
        keyboard.add_hotkey('ctrl+windows+alt+x', lambda: os.execv(sys.executable, [sys.executable, script_path] + sys.argv[1:]))

        def open_history_file():
            script_dir = os.path.dirname(os.path.abspath(__file__))
            file_path = os.path.join(script_dir, "悬浮时间输入历史history.txt")
            if os.path.exists(file_path):
                try:
                    if os.name == 'nt':  # Windows 系统
                        os.startfile(file_path)
                    else:  # 其他系统（如 Linux、macOS）
                        subprocess.run(['open', file_path])
                except Exception as e:
                    print(f"打开文件时出错: {e}")
            else:
                print("历史文件不存在")

        keyboard.add_hotkey('ctrl+windows+alt+h', open_history_file)
    except Exception as e:
        print(f"注册热键时出错: {e}")
    
    sys.exit(app.exec_())
